'use strict';

const {
	Controller
} = require('uni-cloud-router');
const dbcmd = uniCloud.database().command;

module.exports = class CouponController extends Controller {
	// 激活
	async activation() {
		let response = {
			code: 1,
			datas: ''
		};

		let start = new Date().getTime();
		// 请求参数
		const req = this.ctx.data;

		let {
			id
		} = req;

		const couponRes = await this.db.collection('wmzmall-marketing-coupon-rule').doc(id).get();
		if (couponRes.data && couponRes.data.length == 1) {
			// 按照规则生成 优惠券
			const couponData = couponRes.data[0];
			if (couponData.state !== '待激活') {
				response.datas = '当前优惠券状态：' + couponData.state;
				return response;
			}

			let couponDatas = [];
			for (let i = 0; i < couponData.num; i++) {
				couponDatas.push({
					coupon_id: id,
					code: this.createCode(),
					type: couponData.type,
					name: couponData.name,
					price: couponData.price,
					member_type: couponData.member_type,
					order_amount: couponData.order_amount,
					per_max: couponData.per_max,
					num: couponData.num,
					start_time: couponData.start_time,
					end_time: couponData.end_time,
					receive_type: couponData.receive_type,
					allow_type: couponData.allow_type,
					allow_ids: couponData.allow_type,
					allow_jsons: couponData.allow_jsons,
					is_share: couponData.is_share,
					state: '待领取',
					note: couponData.note,
					remark: couponData.remark,
					version: 1,
					is_delete: 0,
					create_time: start,
					create_uid: this.ctx.auth.uid,
					create_uname: this.ctx.auth.userInfo.username
				});
			}

			if (couponDatas.length > 0) {
				await this.db.collection('wmzmall-marketing-coupon').add(couponDatas);
			}

			await this.db.collection('wmzmall-marketing-coupon-rule').doc(id).update({
				state: '运营中',
				last_modify_time: start,
				last_modify_uid: this.ctx.auth.uid,
				last_modify_uname: this.ctx.auth.userInfo.username
			});

			response.datas = '激活成功';
		}


		let end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}
	// 赠送
	async gift() {
		let response = {
			code: 1,
			datas: ''
		};

		/**
		 * 1. 根据优惠券规则ID获取规则数据
		 * 2. 根据优惠券规则ID获取总赠送数的待领取优惠券数据
		 * 2.1 判断优惠券剩余数量是否满足总赠送数
		 * 3. 根据赠送用户ids获取用户数据
		 * 4. 修改优惠券规则已领取数量、操作时间
		 * 5. 循坏赠送用户数据
		 * 5.1 修改用户优惠券数量
		 * 6. 修改已领取的优惠券用户数据，状态 -> 已领取
		 */

		let start = new Date().getTime();
		// 请求参数
		const req = this.ctx.data;

		let {
			id,
			giftData
		} = req;

		// 1. 根据优惠券规则ID获取规则数据
		const couponRuleRes = await this.db.collection('wmzmall-marketing-coupon-rule').doc(id).get();
		if (!(couponRuleRes.data && couponRuleRes.data.length === 1)) {
			response.msg = `优惠券规则[${id}]数据不存在`;
			return response;
		}
		const couponRuleData = couponRuleRes.data[0];
		if (couponRuleData.state !== '运营中') {
			response.msg = `优惠券状态[${couponRuleData.state}]，禁止赠送`;
			return response;
		}
		if (couponRuleData.receive_type !== '主动发放') {
			response.msg = `优惠券领取方式[${couponRuleData.state}]，禁止赠送`;
			return response;
		}
		if (couponRuleData.per_max > giftData.num && couponRuleData.per_max != 0) {
			response.msg = `赠送数[${giftData.num}]超过可领数[${couponRuleData.per_max}]`;
			return response;
		}

		// 2. 根据优惠券规则ID获取总赠送数的待领取优惠券数据
		const couponRes = await this.db.collection('wmzmall-marketing-coupon').aggregate().match({
				coupon_id: id,
				state: "待领取"
			}).limit((giftData.num) * (giftData.openids.length))
			.end();
		// 2.1 判断优惠券剩余数量是否满足总赠送数
		if (giftData.num > couponRes.data.length) {
			response.msg = `赠送数[${giftData.num}]超过剩余数[${couponRes.data.length}]`;
			return response;
		}
		// 优惠券 ids
		let couponIds = couponRes.data.map(x => x._id);

		// 3. 根据赠送用户ids获取用户数据
		const userRes = await this.db.collection('wmzmall-member').field({
			_id: true,
			member_guid: true,
			member_name: true,
			member_nickname: true,
			member_mobile: true,
			member_headimg: true,
			member_openid: true
		}).where({
			_id: this.db.command.in(giftData.openids)
		}).get();

		uniCloud.logger.info("couponRuleRes", couponRuleRes);
		uniCloud.logger.info("couponRes", couponRes);
		uniCloud.logger.info("userRes", userRes);

		// 4. 修改优惠券规则 累计已领取数量、记录操作时间
		await this.db.collection('wmzmall-marketing-coupon-rule').doc(id).update({
			receive_num: this.db.command.inc((giftData.num) * (giftData.openids.length)),
			last_modify_time: start,
			last_modify_uid: this.ctx.auth.uid,
			last_modify_uname: this.ctx.auth.userInfo.username
		});

		// 5. 循坏赠送用户数据
		for(let i = 0; i < userRes.data.length; i++){
			// 5.1 修改用户优惠券数量
			await this.db.collection('wmzmall-member').doc(userRes.data[i]._id).update({
				member_coupon_cnt: this.db.command.inc(giftData.num)
			});
			
			// 处理每一个用户赠送数量
			let arr = couponIds.splice(0, giftData.num);
			
			// 6. 修改已领取的优惠券用户数据，状态 -> 已领取
			await this.db.collection('wmzmall-marketing-coupon').where({
				_id: this.db.command.in(arr)
			}).update({
				member_id: userRes.data[i]._id,
				member_openid: userRes.data[i].member_openid,
				member_name: userRes.data[i].member_name || userRes.data[i].member_nickname,
				member_headimg: userRes.data[i].member_headimg,
				last_modify_time: start,
				last_modify_uid: this.ctx.auth.uid,
				last_modify_uname: this.ctx.auth.userInfo.username,
				state: '已领取'
			});
		}

		response.datas = '赠送成功';

		let end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}
	// 删除
	async remove() {
		let response = {
			code: 1,
			datas: ''
		};

		let start = new Date().getTime();
		// 请求参数
		const req = this.ctx.data;

		let {
			ids,
			couponId
		} = req;

		uniCloud.logger.info(ids, couponId);

		await this.db.collection('wmzmall-marketing-coupon').where({
			_id: this.db.command.in(ids)
		}).remove();

		await this.db.collection('wmzmall-marketing-coupon-rule').doc(couponId).update({
			num: this.db.command.inc(-ids.length)
		});

		let end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}

	createCode() {
		/****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
		let chars = 'ABCDEFGHJKLMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
		let maxPos = chars.length;
		let code = '';
		for (let i = 0; i < 6; i++) {
			code += chars.charAt(Math.floor(Math.random() * maxPos));
		}

		return code;
	}
}
